layui.use(['jquery'], function(){
	ready(layui.$);
});
// 获取数组中的最大值 
// arr: 数组
// value：如果数组项是对象，则表示对象中表示数值的key值
// function getArrayMax(arr, value) {
// 	if ( Object.prototype.toString.call(arr) === '[object Array]' ) {
// 		if ( Object.getOwnPropertyNames(arr[0]).length )
// 		return Math.max.apply(Math, arr);
// 	}
// };
// 父级菜单(有子菜单)
function menuParent(parent, childrens) {
	if ( parent.url ) {
		return '<li class="layui-nav-item"><a href='+parent.url+'>'+parent.name+'</a></li>';
	} else {
		var cdf_c = document.createDocumentFragment();
		var cdf_p = [
			'<li class="layui-nav-item">'
			,'<a class="noTab" href="javascript:;">'+parent.name+'</a>'
			,'<dl class="layui-nav-child">'
			,'</dl></a></li>'
		];
	
		for ( var i = 0; i < childrens.length; i++ ) {
			if ( childrens[i].url[0] === '/' ) {
				childrens[i].url = childrens[i].url.substr(1);
			}
			cdf_c = '<dd><a href="javascript:;" data-url='+childrens[i].url+'>'+childrens[i].name+'</a></dd>';
			cdf_p.splice(cdf_p.length-1, 0, cdf_c);
		}
	
		return cdf_p.join('');
	}
};
function analysisMenuJson(obj, $) {
	var menu_platform	= JSON.parse(JSON.stringify(new Object()));
	var menu_child 		= JSON.parse(JSON.stringify(new Object()));
	var menu_parent 	= JSON.parse(JSON.stringify(new Object()));
	var treeRootDom		= $('.layui-nav-tree');
	for ( var key in obj ) {
		if ( !obj[key].parentId ) {
			menu_platform[obj[key].id] = obj[key];
		} else if ( +obj[key].level === 1 ) {
			menu_parent[obj[key].id] = obj[key];
		} else if ( +obj[key].level === 2 ) {
			menu_child[obj[key].id] = obj[key];
		}
	}

	var key,k;
	var hasown = Object.prototype.hasOwnProperty;
	var arr_parent = [];
	for ( key in menu_parent ) {
		if(hasown.call(menu_parent, key)){
			arr_parent[arr_parent.length] = menu_parent[key];
			(function(){
				if ( Object.getOwnPropertyNames(menu_parent).length === arr_parent.length ) {
					arr_parent = arr_parent.sort(compareArrObj('code', 'asc'));
					arr_parent.sort(function(x,y){return x.createTime < y.createTime ? -1 : 1 });

					for ( var i = 0, len = arr_parent.length; i < len; i++ ) {
						var arr_child		= [];
						for ( k in menu_child ) {
							if ( hasown.call(menu_child, k) && arr_parent[i].id === menu_child[k].parentId ) {
								arr_child[arr_child.length] = menu_child[k];
							}
						}
						arr_child = arr_child.sort(compareArrObj('code', 'asc'));
						treeRootDom.append(menuParent(arr_parent[i], arr_child));
					}
				}
			})(arr_parent);
		}
	}
	
};
//var serverHttp = localStorage.serverHttp || 'http://localhost:8080';
function ready($, type) {
	var userFun 	= new _user();
	var leftMenuFun = new _leftMenu();
	var loaclUser 	= localStorage.user ? JSON.parse(localStorage.user) : new Object();
	var loaclMenu 	= localStorage.menu ? JSON.parse(localStorage.menu) : new Object();
	var localToken	= localStorage.token ? JSON.parse(localStorage.token) : new Object();
	var user;		// 用户信息
	var leftMenu;	// 菜单信息

	if ( $('.layui-layer-title').length ) $('.layui-layer-title').remove();

	for ( var key in loaclUser ) {
		userFun.setData(key, loaclUser[key]);
	}
	user = userFun.getData();
	// localStorage.removeItem('user');

	for ( var i = 0, len = loaclMenu.length; i < len; i++ ) {
		leftMenuFun.setData(i, loaclMenu[i]);
	}
	leftMenu = leftMenuFun.getData();
	analysisMenuJson(leftMenu, $);
	// localStorage.removeItem('menu');

	document.getElementById('userName').innerText = user.userName || '用户名';

	if ( '{}' === JSON.stringify(loaclUser) ) {
		console.error('用户没登录哦！');
		// 用户未登录的话  直接跳转到登录页（前端解决方案）
		window.open('login.html', '_self');
	}
	if ( '{}' === JSON.stringify(localToken) ) {
		console.error('无token');
	} else {
		userFun.setData('token', localToken);
		// localStorage.removeItem('token');
	}
	if ( !type ) {
		$('.layui-nav-item').on('click', '#quitLogin', function(){
			var that = this;
			if ( '{}' === JSON.stringify(userFun.getData()) ) {
				layer.confirm('您并没有登录！是否立即登录？', {
					icon: 7,
					title: '提示',
					  btn: ['是','否'] //按钮
				}, function(){
					$(that).parent('.layui-nav-item').removeClass('layui-this');
					location.href = location.href.substr(0, location.href.lastIndexOf('/'))+'/login.html';
				}, function(){
					$(that).parent('.layui-nav-item').removeClass('layui-this');
					// 否
				});
				return;
			}
			$.ajax({
				url: '/logout?_token='+userFun.getData('token'),
				type: 'post',
				dataType: 'json',
				data: '',
				crossDomain: true
				// beforeSend: function(request) {
	   //            	request.setRequestHeader("Authorization", userFun.getData('token'));
	   //       	},
			})
			.done(function(res) {
				if ( 1 === res.status ) {
					userFun.clearData();
					leftMenuFun.clearData();
					document.getElementById('userName').innerText = user.userName || '用户名';
					localStorage.removeItem('user');
					localStorage.removeItem('menu');
					localStorage.removeItem('token');
					layer.msg('成功退出登录！');
                    setTimeout(function(){
                        //location.href = location.href+"index.html";
                        location.href = location.href.substr(0, location.href.lastIndexOf('/index.html'))+'/login.html';
                    }, 1000);

					ready($, 'quit'); 
				}
			})
			.fail(function(res) {
				layer.msg(res.msg);
			})
			.always(function() {
				$(that).parent('.layui-nav-item').removeClass('layui-this');
			});
		});
	}

	var chart = echarts.init(document.getElementById('echarts-map'));
	var chart2= echarts.init(document.getElementById('echarts-pyramid'));
    chart.setOption({
		title : {
	        text: '地图展示功能技术预研',
	        subtext: '区块根据值域的不同而呈现不同的色值',
	        x: 'center'
	    },
	    tooltip : {
	        trigger: 'item',
	        formatter: function(params) {  
                var res = params.name+'<br/>';  
                var myseries = chart.getOption().series;  
                for (var i = 0; i < myseries.length; i++) {  
                    for(var j=0;j<myseries[i].data.length;j++){  
                        if(myseries[i].data[j].name==params.name){  
                            res+=myseries[i].name +' : '+myseries[i].data[j].value+'</br>';  
                        }  
                    }  
                }  
                return res;
            }
	    },
	    // dataRange: {
	    //     x: 'left',
	    //     y: 'bottom',
	    //     splitList: [
	    //         {start: 1500, color: 'purple'},
	    //         {start: 900, end: 1500, color: 'blue'},
	    //         {start: 310, end: 1000, color: 'green'},
	    //         {start: 200, end: 300, color: 'yello'},
	    //         {start: 10, end: 200, label: '10 到 200（自定义label）', color: 'orange'},
	    //         {start: 5, end: 5, label: '5（自定义特殊颜色）', color: 'red'},
	    //         {end: 10}
	    //     ]
	    // },
	    visualMap: {
	        textStyle: {
	            color: '#fedcba'
	        },
	        min: 0,
	        max: 2000,
	        left: 'left',
	        top: 'bottom',
	        text: ['高', '低'], // 文本，默认为数值文本
	        calculable: false
	        // color: ['#0000F8', '#33F4FA']
	    },
	    series : [
	        {
	            name: '根据什么来划域',
	            type: 'map',
	            mapType: 'china',
	            roam: true,
	            mapValueCalculation: 'max',
	            itemStyle:{
	                normal:{
	                    label:{
	                        show:false,
	                        textStyle: {
	                           color: "rgb(249, 249, 249)"
	                        }
	                    }
	                },
	                emphasis:{label:{show:false}}
	            },
	            data:[
	                {name: '北京',value: Math.round(Math.random()*2000)},
	                {name: '天津',value: Math.round(Math.random()*2000)},
	                {name: '上海',value: Math.round(Math.random()*2000)},
	                {name: '重庆',value: Math.round(Math.random()*2000)},
	                {name: '河北',value: 0},
	                {name: '河南',value: Math.round(Math.random()*2000)},
	                {name: '云南',value: 5},
	                {name: '辽宁',value: 305},
	                {name: '黑龙江',value: Math.round(Math.random()*2000)},
	                {name: '湖南',value: 200},
	                {name: '安徽',value: Math.round(Math.random()*2000)},
	                {name: '山东',value: Math.round(Math.random()*2000)},
	                {name: '新疆',value: Math.round(Math.random()*2000)},
	                {name: '江苏',value: Math.round(Math.random()*2000)},
	                {name: '浙江',value: Math.round(Math.random()*2000)},
	                {name: '江西',value: Math.round(Math.random()*2000)},
	                {name: '湖北',value: Math.round(Math.random()*2000)},
	                {name: '广西',value: Math.round(Math.random()*2000)},
	                {name: '甘肃',value: Math.round(Math.random()*2000)},
	                {name: '山西',value: Math.round(Math.random()*2000)},
	                {name: '内蒙古',value: Math.round(Math.random()*2000)},
	                {name: '陕西',value: Math.round(Math.random()*2000)},
	                {name: '吉林',value: Math.round(Math.random()*2000)},
	                {name: '福建',value: Math.round(Math.random()*2000)},
	                {name: '贵州',value: Math.round(Math.random()*2000)},
	                {name: '广东',value: Math.round(Math.random()*2000)},
	                {name: '青海',value: Math.round(Math.random()*2000)},
	                {name: '西藏',value: Math.round(Math.random()*2000)},
	                {name: '四川',value: Math.round(Math.random()*2000)},
	                {name: '宁夏',value: Math.round(Math.random()*2000)},
	                {name: '海南',value: Math.round(Math.random()*2000)},
	                {name: '台湾',value: Math.round(Math.random()*2000)},
	                {name: '香港',value: Math.round(Math.random()*2000)},
	                {name: '澳门',value: Math.round(Math.random()*2000)}
	            ]
	        },
	        {
	        	name: '第二个名字',
	            type: 'map',
	            mapType: '',
	            data:[
	                {name: '北京',value: Math.round(Math.random()*2000)},
	                {name: '天津',value: Math.round(Math.random()*2000)},
	                {name: '上海',value: Math.round(Math.random()*2000)},
	                {name: '重庆',value: Math.round(Math.random()*2000)},
	                {name: '河南',value: Math.round(Math.random()*2000)},
	                {name: '云南',value: 5},
	                {name: '辽宁',value: 305},
	                {name: '黑龙江',value: Math.round(Math.random()*2000)},
	                {name: '湖南',value: 200},
	                {name: '安徽',value: Math.round(Math.random()*2000)},
	                {name: '山东',value: Math.round(Math.random()*2000)},
	                {name: '新疆',value: Math.round(Math.random()*2000)},
	                {name: '江苏',value: Math.round(Math.random()*2000)},
	                {name: '浙江',value: Math.round(Math.random()*2000)},
	                {name: '江西',value: Math.round(Math.random()*2000)},
	                {name: '湖北',value: Math.round(Math.random()*2000)},
	                {name: '广西',value: Math.round(Math.random()*2000)},
	                {name: '甘肃',value: Math.round(Math.random()*2000)},
	                {name: '山西',value: Math.round(Math.random()*2000)},
	                {name: '内蒙古',value: Math.round(Math.random()*2000)},
	                {name: '陕西',value: Math.round(Math.random()*2000)},
	                {name: '吉林',value: Math.round(Math.random()*2000)},
	                {name: '福建',value: Math.round(Math.random()*2000)},
	                {name: '贵州',value: Math.round(Math.random()*2000)},
	                {name: '广东',value: Math.round(Math.random()*2000)},
	                {name: '青海',value: Math.round(Math.random()*2000)},
	                {name: '西藏',value: Math.round(Math.random()*2000)},
	                {name: '四川',value: Math.round(Math.random()*2000)},
	                {name: '宁夏',value: Math.round(Math.random()*2000)},
	                {name: '海南',value: Math.round(Math.random()*2000)},
	                {name: '台湾',value: Math.round(Math.random()*2000)},
	                {name: '香港',value: Math.round(Math.random()*2000)},
	                {name: '澳门',value: Math.round(Math.random()*2000)}
	            ]
	        }
	    ]

    });
	// chart.showLoading();	加载动画
	chart.on('click', function (param){
		console.log(param);
	});
	chart.on('georoam', function (params) {
	    // 缩放 拖动 触发事件
	});
	
	chart2.setOption({
	    tooltip : {
	        trigger: 'axis',
	        axisPointer : {
	            type: 'shadow'
	        }
	    },
	    legend: {
	        data:['直接访问','邮件营销','联盟广告','视频广告','搜索引擎']
	    },
	    color:['red','orange','yellow','green','blue'],
	    toolbox: {
	        show : true,
	        // orient : 'vertical',
	        orient : 'horizontal',
	        y : '20',
	        x : 'center',
	        feature : {
	            mark : {show: true},
	            magicType : {show: true, type: ['bar', 'line']},
	            restore : {show: true},
	            saveAsImage : {show: true}
	        }
	    },
	    calculable : true,
	    xAxis : [
	        {
	            type : 'category',
	            data : ['周一','周二','周三','周四','周五','周六','周日']
	        }
	    ],
	    yAxis : [
	        {
	            type : 'value',
	            splitArea : {show : true}
	        }
	    ],
	    grid: {
	        x2:40
	    },
	    series : [
	        {
	            name:'直接访问',
	            type:'bar',
	            stack: '总量',
	            data:[320, 332, 301, 334, 390, 330, 320]
	        },
	        {
	            name:'邮件营销',
	            type:'bar',
	            stack: '总量',
	            data:[120, 132, 101, 134, 90, 230, 210]
	        },
	        {
	            name:'联盟广告',
	            type:'bar',
	            stack: '总量',
	            data:[220, 182, 191, 234, 290, 330, 310]
	        },
	        {
	            name:'视频广告',
	            type:'bar',
	            stack: '总量',
	            data:[150, 232, 201, 154, 190, 330, 410]
	        },
	        {
	            name:'搜索引擎',
	            type:'bar',
	            stack: '总量',
	            data:[820, 932, 901, 934, 1290, 1330, 1320]
	        }
	    ]
	})
    
};
